use super::server::get_json_server_url;
use crate::handlers::server::get_img_server_url;
use crate::models::home::{HomeLink, HomeList, HomeListApp};
use crate::utils::format::format_icon_url;
use crate::utils::UA;

#[tauri::command]
pub async fn get_home_links() -> Result<Vec<HomeLink>, String> {
    let json_server_url = get_json_server_url();
    let img_server_url = get_img_server_url();
    let url = format!("{}/home/homelinks.json", json_server_url);

    let client = reqwest::Client::new();
    let response = client
        .get(&url)
        .header("User-Agent", UA)
        .send()
        .await
        .map_err(|e| e.to_string())?;

    // 获取响应内容的文本形式
    let response_text = response.text().await.map_err(|e| e.to_string())?;

    // 将文本解析为 HomeLink 向量
    let mut links: Vec<HomeLink> =
        serde_json::from_str(&response_text).map_err(|e| e.to_string())?;

    // 为每个 HomeLink 的 img_url 添加图片服务器前缀
    for link in &mut links {
        link.img_url = format!("{}{}", img_server_url, link.img_url);
    }

    Ok(links)
}

#[tauri::command]
pub async fn get_home_list_apps(json_url: String) -> Result<Vec<HomeListApp>, String> {
    let json_server_url = get_json_server_url();
    let url = format!("{}{}", json_server_url, json_url);

    let client = reqwest::Client::new();
    let response = client
        .get(&url)
        .header("User-Agent", UA)
        .send()
        .await
        .map_err(|e| e.to_string())?;

    let response_text = response.text().await.map_err(|e| e.to_string())?;

    let mut apps: Vec<HomeListApp> =
        serde_json::from_str(&response_text).map_err(|e| e.to_string())?;

    for app in &mut apps {
        app.icon = Some(format_icon_url(&app.category, &app.pkgname));
    }

    Ok(apps)
}

#[tauri::command]
pub async fn get_home_lists() -> Result<Vec<HomeList>, String> {
    let json_server_url = get_json_server_url();
    let url = format!("{}/home/homelist.json", json_server_url);

    let client = reqwest::Client::new();
    let response = client
        .get(&url)
        .header("User-Agent", UA)
        .send()
        .await
        .map_err(|e| e.to_string())?;

    let response_text = response.text().await.map_err(|e| e.to_string())?;

    let lists: Vec<HomeList> = serde_json::from_str(&response_text).map_err(|e| e.to_string())?;

    Ok(lists)
}
